#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>

#define MAXSIZE 1024
//#define COUNT 
//#define MUTEX

pthread_mutex_t mutex;
sem_t sem;
#ifdef COUNT
static int count =1;
#endif

char message[]={"hello world"};

//copy memssage function
void *thread_copy(void *arg)  
{
//	pthread_detach(pthread_self());
	printf("this function is copy, Args is %s\n", (char *)arg);
	sleep(2);
	strcpy(message, "Bye");
	pthread_exit(0);
}
#ifdef COUNT
void *thread_cnt()
{
	pthread_detach(pthread_self());
	pthread_mutex_lock(&mutex);	
	if(count %10  ==0)
		printf("create thread %d\n", count);
	count++;
	pthread_mutex_unlock(&mutex);
	pthread_exit(0);
}
#endif
int main()
{
	int err,res;
	int i=0;
	pthread_t tid;
	pthread_attr_t attr;
	size_t size = 32*1024;
	void *join_result;
	int scope=PTHREAD_SCOPE_PROCESS;
	char buffer[MAXSIZE]={0};
	struct sched_param param;
 
 //thread attribute
	pthread_attr_init(&attr);  
	pthread_attr_setstacksize(&attr, size);    //stack size
	pthread_attr_setscope(&attr, scope);       //isbind to system 
	pthread_attr_getschedparam(&attr,&param);   //priporitys
	param.sched_priority=10;
	pthread_attr_setschedparam(&attr, &param);
	pthread_attr_setdetachstatus(&attr, PTHREAD_CREATE_DETACHED);   //detach
	pthread_mutex_init(&mutex, NULL);
#ifdef COUNT
	while(1)
	{
		err = pthread_create(&tid, &attr, thread_cnt, NULL);
		if(err != 0)
		{
			printf("thread create error\n");
			exit(0);
		}
	}
#endif
	for(i=0; i<3; i++)
	{	
	#ifdef MUTEX
		pthread_mutex_lock(&mutex);
		scanf("input a %s: ", buffer);
		pthread_mutex_unlock(&mutex);
	 #endif 
	 #if 0
  		if(sem_init(&sem, 0, 0)!=0)
 		{	
  			printf("sem init failed\n");
			exit(0);
  		}
  		sem_wait(&sem);
		scanf("input %s: ", buffer);
		sem_post(&sem);  	
	#endif	
		err = pthread_create(&tid, &attr, thread_copy, (void *)message);
		if(err != 0)
		{
			printf("thread create error\n");
			exit(0);
		}
		res = pthread_join(tid, &join_result);
		if(res != 0)
		{
			printf("thread join failed\n");
			exit(0);
		}
	//	printf("thread join return is %s\n",(char *)join_result);
	//	printf("message is %s\n", message);
	#ifdef MUTEX
		pthread_mutex_lock(&mutex);
		printf("input %d lenght data\n", strlen(buffer));
		pthread_mutex_unlock(&mutex);
	#endif
	#if 0
		sem_wait(&sem);
		printf("input %d lenght data\n", strlen(buffer));
		sem_post(&sem);
	#endif
	}
    pthread_mutex_destroy(&mutex);
  //sem_destroy(&sem);
    pthread_attr_destroy(&attr);
 #ifdef COUNT
    printf("thread count :%d, stack size :%d\n", count, size);
 #endif
    return 0;
}
